class Solution {
    public int[][] generateMatrix(int n) {
        int cur = 1;
        int cycle = 0;
        int max = n * n;
        int[][] res = new int[n][n];
        // 螺旋剥洋葱法
        while(cur <= max) {
            for(int i = cycle; i < n - cycle; i++) {
                res[cycle][i] = cur ++; 
            }

            for(int i = cycle + 1; i < n - cycle; i++) {
                res[i][n - cycle - 1] = cur ++; 
            }

            for(int i = n - cycle - 2; i >= cycle; i--) {
                res[n - cycle - 1][i] = cur ++; 
            }

             for(int i = n - cycle - 2; i > cycle; i--) {
                res[i][cycle] = cur ++; 
            }
            cycle ++;
        }
        return res;
    }
}